﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;

namespace Marking
{
	class Check
	{
		private int[] tran = { 6, 7, 8, 9, 10, 11 }; //列序号
		public delegate void ReturnMsg(int v);
		public ReturnMsg ReturnProgress;
		public void CheckAlgorithm(Database_mag data_mag, string private_key, int row_mod, int col_mod, int bit_mod)
		{
			ReturnProgress?.Invoke(10);
			DateTime t1 = DateTime.Now;
			Console.WriteLine(t1.ToString());
			TimeSpan ts1 = new TimeSpan(t1.Ticks);
			DataTable dt = data_mag.Read_table();
			int cnt = 0;
			int ccnt = 0;
			int marked = 0;
			int sum = dt.Rows.Count;
			Console.WriteLine("Now read table");
			foreach (DataRow row in dt.Rows)
			{
				ccnt++;
				ReturnProgress?.Invoke(10 + ccnt / sum * 40);
				int hash = GetHash(private_key + row[0].ToString());
				if (hash % row_mod == 0)
				{
					marked++;
					int col = (hash % col_mod + col_mod) % col_mod;
					col = tran[col];
					int bit = (hash % bit_mod + bit_mod - 1) % bit_mod + 1;
					string pre_val = row[col].ToString();
					int len = pre_val.Length;
					if (Convert.ToInt32(pre_val[len-bit]) - '0' == bit)
						cnt++;
				}
			}
			ReturnProgress?.Invoke(50);
			ReturnProgress?.Invoke(100);
			DateTime t2 = DateTime.Now;
			Console.WriteLine(t2.ToString());
			TimeSpan ts2 = new TimeSpan(t2.Ticks);
			TimeSpan ts3 = ts2.Subtract(ts1);
			MessageBox.Show(string.Format("共检测到{0}条水印，匹配百分比{1}%,用时{2}秒", cnt, (cnt * 1.0 / marked) * 100, (ts3.TotalMilliseconds / 1000).ToString()));
			return;
		}

		private int GetHash(string str)
		{
			byte[] sourcebytes = Encoding.Default.GetBytes(str);
			MD5 md5 = new MD5CryptoServiceProvider();
			byte[] hashedbytes = md5.ComputeHash(sourcebytes);
			return BitConverter.ToInt32(hashedbytes, 0);
		}
	}
}
